using UnityEngine;
using LitJson;
#if !UNITY_WEBGL
using RenderHeads.Media.AVProVideo;
#endif

namespace CGF
{
    public partial class PanelSampleVideo : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
#if !UNITY_WEBGL
        private MediaPlayer mediaPlayer;
#endif
        private bool timesUp, checkDevicesSuccess;
        private float popupDialogDelay = 2f;

        //app标签: 1-TikTok 2-Tinder 3-Waplog 4-Badoo
        public enum AppType
        {
            TikTok = 1,
            RedNote = 2,
            DouYin = 3,
            Waplog = 4,
            Tinder = 5,
            Badoo = 6,
        }

        public static void Open()
        {
#if !UNITY_WEBGL
            UIManagerComponent.instance.OpenUI<PanelSampleVideo>(UILayer.Normal, RootComponent.instance, true);
#else
            Debug.LogError("H5版不支持投屏");
#endif
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelSampleVideo>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelSampleVideo", layer, isFloat);
            BindProperties(transform);

            EventManager.Add<Event_PluginMsg>(OnPluginMsg);
            gameObject.transform.DOAlpha(0, true);

            if (Application.isEditor)
            {
                checkDevicesSuccess = true;
            }
            else
            {
                CheckDevicesValid(AppType.Waplog, false);
            }

#if !UNITY_WEBGL
            mediaPlayer = Video.GetComponent<MediaPlayer>();
            mediaPlayer.Events.AddListener((arg0, type, code) =>
            {
                switch (type)
                {
                    case MediaPlayerEvent.EventType.FirstFrameReady:
                        PlayVideo();
                        break;
                }
            });
            Wait.Open();
            //string url = $"{CGFConfig.Instance.ResServerType}/res/{CGFConfig.Instance.ReleaseArea}/{CGFConfig.Instance.Tag}/{CGFConfig.Platform}/movie.mp4";
            string url = "movie.mp4";
            Debug.Log($"播放视频：{url}");
            mediaPlayer.OpenMedia(MediaPathType.RelativeToStreamingAssetsFolder, url);
            TipFakeOut();
#endif
        }

        private async void TipFakeOut()
        {
            await CTask.Wait(2);
            Tip.transform.DOAlpha(0, 0.5f);
        }

        private async void PlayVideo()
        {
            Wait.Close();
            gameObject.transform.DOAlpha(1, 0.5f, true);
            await CTask.Wait(popupDialogDelay);
            timesUp = true;
            OpenDialog(60);
        }

        private void CheckDevicesValid(AppType appType, bool forLogin)
        {
            JsonData config = new JsonData();
            JsonData language = new JsonData();
            language["开始"] = I18N_开始;
            language["进行中"] = I18N_进行中;
            language["体验中"] = I18N_体验中;
            language["完成"] = I18N_完成;
            language["查看全部任务"] = I18N_查看全部任务;
            language["关闭查看任务"] = I18N_关闭查看任务;
            language["正在启动目标app"] = I18N_正在启动目标app;
            language["准备登录用户账号"] = I18N_准备登录用户账号;
            language["正在登录账号"] = I18N_正在登录账号;
            language["登录成功"] = I18N_登录成功;
            language["回复消息"] = I18N_回复消息;
            language["预估耗时"] = I18N_预估耗时;
            language["暂无设备在线"] = I18N_暂无设备在线;
            language["暂无锁定设备"] = I18N_暂无锁定设备;
            language["距离体验结束还有"] = I18N_距离体验结束还有;

            config["language"] = language;
            config["app_index"] = (int)appType - 1;
            config["is_login"] = forLogin;

            config["api_base_url"] = Config.brazil.APIBaseUrl;
            config["ws_base_url"] = Config.brazil.VideoPluginWsUrl;

            config["test_device_id"] = ""; //插件可能填了一个测试设备码，必选传一个空串过去覆盖
            config["can_video_log"] = false;
            config["show_debug_ui"] = false;
            config["access_token"] = UserInfo.Token;
            JsonData appVisibles = new JsonData();
            appVisibles.Add(true);
            appVisibles.Add(false);
            appVisibles.Add(true);
            appVisibles.Add(false);
            config["app_visibles"] = appVisibles;
            Debug.Log($"config.ToJson(): {config.ToJson()}");
            AndroidHelper.CallStaticFunction("com.plugin.h264player.AndroidPlugin", "openVideoPanel", AndroidHelper.CurrActivity, config.ToJson());
        }

        private void OnPluginMsg(Event_PluginMsg e)
        {
            Wait.Close();
            string content;
            JsonData json = JsonMapper.ToObject(e.msg);
            switch (json["cmd"].ToString())
            {
                case "cmd":
                    content = json["data"].ToString();
                    if (content == "success")
                    {
                        checkDevicesSuccess = true;
                        OpenDialog(60);
                        return;
                    }
                    else if (content == "close")
                    {
                        Close();
                        return;
                    }
                    break;
                case "alert":
                    content = json["data"].ToString();
                    if (content == "have_no_devices")
                    {
                        Dialog.Alert(I18N_have_no_devices);
                    }
                    else if (content == "have_no_locked_devices")
                    {

                        Dialog.Alert(I18N_have_no_devices);
                    }
                    else
                    {
                        Dialog.Alert(content);
                    }
                    break;
            }
            Close();
        }

        public void OpenDialog(int expSeconds)
        {
            if (!checkDevicesSuccess || !timesUp) return;
            if (Application.isEditor)
            {
                Dialog.Alert("仅真机支持", Close);
                return;
            }
            AndroidHelper.CallStaticFunction("com.plugin.h264player.AndroidPlugin", "openDialog", AndroidHelper.CurrActivity, expSeconds);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            EventManager.Remove<Event_PluginMsg>(OnPluginMsg);
        }

    }
}
